package net.liuyimin.service;

import net.liuyimin.util.ZkClient;
import net.liuyimin.util.ZkDistributedLock;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class StockService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private ZkClient zkClient;

    /**
     * 基于Zookeeper实现分布式锁
     */
    public void deductByZk() {
        // 加锁，获取锁失败重试
        ZkDistributedLock lock = this.zkClient.getZkDistributedLock("lock");
        lock.lock();

        try {
            // 1.查询库存信息
            String stock = this.stringRedisTemplate.opsForValue().get("stock").toString();
            // 2.判断库存是否充足
            if (stock != null && stock.length() != 0) {
                Integer st = Integer.valueOf(stock);
                if (st > 0) {
                    // 3.扣减库存
                    this.stringRedisTemplate.opsForValue().set("stock", String.valueOf(--st));
                }
            }
        } finally {
            // 释放锁
            lock.unlock();
        }
    }

}
